package com.zzyl.nursing.service.impl;

import java.util.*;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.stream.Collectors;

/**
 * 老人家属Service业务层处理
 *
 * @author guo
 * @date 2024-11-17
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatServiceImpl wechatService;

    @Autowired
    private TokenService tokenService;

    private static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {

        //2.1 调用微信接口获取openId,phone
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        //2.2 通过openId查询家人信息是否存在
        FamilyMember familyMember = lambdaQuery().ge(FamilyMember::getOpenId, openId).one();
        //2.3 不存在则添加家人信息
        if (Objects.isNull(familyMember)) {
            //得到一个名字
            int idx = (int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size());
            String nickName = DEFAULT_NICKNAME_PREFIX.get(idx) + StringUtils.substring(phone, 7);
            /*familyMember = new FamilyMember();
            familyMember.setName(nickName);
            familyMember.setOpenId(openId);
            familyMember.setPhone(phone);
            save(familyMember);*/
            //构建者模式
            familyMember = familyMember.builder().name(nickName).openId(openId).phone(phone).build();
        }else {
            //2.4 存在,则检查手机号码是否变更, 变更则更新家人手机号码
            if (!Objects.equals(familyMember.getPhone(),phone)) {
                //member.setPhone(phone);
                //updateById(member);
                //高并发的情况下,数据会覆盖,所有使用乐观锁来保证数据的一致性
                lambdaUpdate().set(FamilyMember::getPhone,phone)
                        .eq(FamilyMember::getId,familyMember.getId())
                        .update();
            }
        }
        //2.5 生成token
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId",familyMember.getId());
        claims.put("nickName",familyMember.getName());
        //用框架生封装好的工具来生成token
        //在zzyl-nursing-platform中导入zzyl-framework包 将tokenService注入进来
        String token = tokenService.createToken(claims);
        //2.6 返回结果给前端
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);
        return loginVo;
    }
}
